<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="onclick"
            >excel导出</el-button
          >
          <el-button type="primary" size="small" @click="hAdd"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template #default="{ row }">
              {{ formTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="DelClick(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[2, 5, 7, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </el-card>
      <!-- 弹框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="hCloseDialog"
      >
        <empDialog
          ref="empDialog"
          @close="showDialog = false"
          @update-empolyee="hUpdateEmpolyee"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { getEmployeeList, delEmployee } from "@/api/employees";
import empDialog from "./empDialog.vue";
//导入枚举信息
import EmployeeEnum from "@/constant/employees";
const hireType = EmployeeEnum.hireType.reduce((pic, item) => {
  pic[item.id] = item.value;
  return pic;
}, {});
//--------------------------------------------------------------------------------------------------------
export default {
  data() {
    return {
      page: 1, //页码值
      size: 5, //每页条数
      list: [], //保存员工列表
      total: 0, //总条数
      showDialog: false,
    };
  },
  components: {
    empDialog,
  },
  created() {
    //进入页面就获取
    this.loadEmployeeList();
  },
  methods: {
    //将英文转换为中文
    formData(List) {
      const map = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };
      //取出数组
      const one = List[0];
      if (!one) {
        return;
      }

      //console.log(Object.keys(one));//取出英文的键
      //遍历对象
      const header = Object.keys(one).map((enkey) => {
        return map[enkey]; //取到中文的名字
      });
      const data = List.map((item) => {
        item["formOfEmployment"] = hireType[item["formOfEmployment"]];
        return Object.values(item);
      });
      return { header, data };
    },
    //将数据导出到excel表格
    onclick() {
      import("@/vendor/Export2Excel").then(async (excel) => {
        //1每次导出时发送ajax 获取最新数据
        const { data: res } = await getEmployeeList(this.page, this.size);
        // 2.将数据转格式化
        const { header, data } = this.formData(res.rows);
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: "excel-list", // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: "xlsx", // 生成的文件类型
        });
        this.downloadLoading = false;
      });
    },
    //设置时间格式化
    formTime(timer) {
      return dayjs(timer).format("YYYY-MM-DD");
    },
    //弹层发生变化时触发
    hCloseDialog() {
      this.$refs.empDialog.resetForm();
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false;
      //添加成功后跳到最后一页
      this.total++;
      this.page = Math.ceil(this.total / this.size);
      this.loadEmployeeList();
    },
    //格式化聘用形式
    formOfEmploymentFormat(val) {
      return hireType[val] ? hireType[val] : "未知";
    },
    //每页条数
    handleSizeChange(val) {
      this.page = 1;
      this.size = val;
      //刷新页面
      this.loadEmployeeList();
    },
    // 当前页码
    handleCurrentChange(val) {
      this.page = val;
      //刷新页面
      this.loadEmployeeList();
    },
    //获取员工列表
    async loadEmployeeList() {
      try {
        const { data: res } = await getEmployeeList(this.page, this.size);
        this.list = res.rows;
        this.total = res.total;
      } catch (error) {}
    },
    async doDel(id) {
      try {
        await delEmployee(id);
        this.$message.success("删除成功");
        if (this.list.length === 1) {
          this.page--;
          if (this.page <= 0) {
            this.page = 1;
          }
        }
        //刷新页面
        this.loadEmployeeList();
      } catch (error) {}
    },
    //删除角色
    DelClick(id) {
      this.$confirm("是否要删除该员工吗？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.doDel(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //新增按钮
    hAdd() {
      this.showDialog = true;
    },
  },
};
</script>